﻿<%@ WebHandler Language="C#" Class="Assesment.Web.AjaxHandler.Administration.UserManagement.sUserRolehandler" %>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;

using Assesment.Library.DataAccess.Administration;
using Assesment.Library.DomainObject.Administration;
using Assesment.Library.DataAccess.Administration.UserManagement;
using Assesment.Library.DomainObject.Administration.UserManagement;

using Assesment.Library.Enum;
using Assesment.Web.Support;

using Newtonsoft.Json.Linq;

namespace Assesment.Web.AjaxHandler.Administration.UserManagement
{
    public class sUserRolehandler : BaseHandler
    {
        private recUserRoleRepo userRoleDal = new recUserRoleRepo(ConfigurationManager.ConnectionStrings["AssesmentConn"].ConnectionString);
        private recLogRepo logDal = new recLogRepo(ConfigurationManager.ConnectionStrings["AssesmentConn"].ConnectionString);
        private string MethodName = string.Empty;

        public override void ProcessRequest(HttpContext context)
        {
            base.ProcessRequest(context);

            MethodName = context.Request.Params["method"];

            context.Response.Clear();
            context.Response.Buffer = true;

            System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.InputStream);
            
            string jsonString = string.Empty;
            jsonString = context.Server.UrlDecode(sr.ReadToEnd());
            JObject jObj = string.IsNullOrEmpty(jsonString) ? null : JObject.Parse(jsonString);

            sr.Close();
            sr.Dispose();

            switch (MethodName.ToLower())
            {
                case ("insert"):
                    context.Response.Write(Insert(context, jObj));
                    break;
                case ("insertbyuser"):
                    context.Response.Write(InsertByUser(context, jObj));
                    break;
                case ("delete"):
                    context.Response.Write(Delete(context));
                    break;
                case ("getdatabyuserid"):
                    context.Response.Write(GetDataByUserId(context));
                    break;
                case ("getdatabyroleid"):
                    context.Response.Write(GetDataByRoleId(context));
                    break;

                default:
                    // do nothing
                    break;
            }

            context.Response.Flush();
            context.Response.End();

        }

        public override bool IsReusable
        {
            get
            {
                return false;
            }
        }

        #region CRUD Handler

        private string Insert(HttpContext context, JObject jo)
        {
            JSONHelper helper = new JSONHelper();

            try
            {
                int roleId = Convert.ToInt32(jo["RoleID"]);
                List<recUserRole> roleUsers = userRoleDal.GetListByRoleID(roleId);
                roleUsers.ForEach(delegate(recUserRole domain)
                {
                    userRoleDal.Delete(domain.UserRoleID);
                });

                string[] userIds = Convert.ToString(jo["UserID"]).Split(',');

                for (int i = 0; i < userIds.Length; i++)
                {
                    recUserRole obj = new recUserRole();
                    obj.UserID = Convert.ToInt32(userIds[i]);
                    obj.RoleID = roleId;
                    
                    obj.CreatedDate = DateTime.Now;
                    obj.CreatedBy = base.UserLoggedIn;

                    userRoleDal.Save(obj);                    
                }

                helper.IsSuccess = true;
                helper.Message = "Data berhasil di simpan !";
            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Insert By Role User";
                log.LogMessage = helper.Message;
                log.LogSource = "sysTuserRole.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        private string InsertByUser(HttpContext context, JObject jo)
        {
            JSONHelper helper = new JSONHelper();

            try
            {
                int UserID = Convert.ToInt32(jo["UserID"]);
                List<recUserRole> roleUsers = userRoleDal.GetListByUserID(UserID);
                roleUsers.ForEach(delegate(recUserRole domain)
                {
                    userRoleDal.Delete(domain.UserRoleID);
                });

                string[] roleIds = Convert.ToString(jo["RoleID"]).Split(',');

                for (int i = 0; i < roleIds.Length; i++)
                {
                    try{
                        recUserRole obj = new recUserRole();
                        obj.RoleID = Convert.ToInt32(roleIds[i]);
                        obj.UserID = UserID;

                        obj.CreatedDate = DateTime.Now;
                        obj.CreatedBy = base.UserLoggedIn;

                        userRoleDal.Save(obj);
                    }
                    catch(Exception ex){
                        if (i == 0)
                        {
                            //do nothing
                        }
                        else
                            throw (ex);
                          
                    }
                    
                    }
                    
                

                helper.IsSuccess = true;
                helper.Message = "Data berhasil di simpan !";
            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Insert By User Role";
                log.LogMessage = helper.Message;
                log.LogSource = "sysTuserRole.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }


        private string Delete(HttpContext context)
        {
            JSONHelper helper = new JSONHelper();

            string[] ids = context.Request.Params["id"].Split(',');
            foreach (string id in ids)
            {
                int intID = Convert.ToInt32(id);

                userRoleDal.Delete(intID);
            }

            helper.IsSuccess = true;            
            helper.Message = "Data berhasil di hapus !";

            helper.IsSuccess = false;
                helper.Message = "";

                recLog log = new recLog();
                log.LogEvent = "Delete";
                log.LogMessage = "";
                log.LogSource = "sRolehandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
            

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }


        public string GetDataByUserId(HttpContext context)
        {
            int UserID = 0;
            int.TryParse(context.Request.Params["UserID"], out UserID);

            List<recUserRole> list = userRoleDal.GetListByUserID(UserID);

            return Newtonsoft.Json.JsonConvert.SerializeObject(list);

        }

        public string GetDataByRoleId(HttpContext context)
        {
            int roleId = 0;
            int.TryParse(context.Request.Params["roleId"], out roleId);

            List<recUserRole> list = userRoleDal.GetListByRoleID(roleId);

            return Newtonsoft.Json.JsonConvert.SerializeObject(list);

        }



        #endregion

    }
}